//
//  KLineMainView.swift
//  JunYiProject
//
//  Created by xiaogxjkz on 2021/6/9.
//

import UIKit
import Charts
import YYKit
import BusinessChat
import SVProgressHUD

class KLineMainView: BaseView {
    
    private var viewModel:GameViewModel?
    private let _font:UIFont = UIFont.systemFont(ofSize: 18, weight: .bold)
    
    /// 右边指标视图宽度
    private let right_view_width:CGFloat = 90 + Setting.K_APP_SAFETY_HEIGHT
    
    /// 背景色
    private let bg_color:UIColor = UIColor.clear
    
    /// 数据总条数
    private let size_count = 90
    
    /// 初始本金
    private let tmoney:Double = 10000
    
    
    //MARK: - override
    override init(ViewModel vm: ViewModelProtocol) {
        self.viewModel = vm as? GameViewModel
        super.init(ViewModel: vm)
        
        //加载数据
        self.loadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /// 设置约束
    override func updateConstraints() {
        
        self.topView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(34)
        }
        
        self.btnBack.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(28.5)
            make.height.equalTo(20)
            make.right.equalTo(-15 - Setting.K_APP_SAFETY_HEIGHT)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        self.imgLogo.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.height.equalTo(22)
            make.left.equalTo(Setting.K_APP_SAFETY_NAV_HEIGHT)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        self.imgLeft.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(22)
            make.height.equalTo(12)
            make.left.equalTo(self.imgLogo.snp.right).offset(20)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        self.imgRight.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(22)
            make.height.equalTo(12)
            make.right.equalTo(self.btnBack.snp.left).offset(-15)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        self.labStep.snp.makeConstraints { [weak self] make in
            guard let self = self else { return }
            make.width.equalTo(180)
            make.height.equalTo(21)
            make.right.equalTo(self.imgRight.snp.left).offset(15)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        self.labYield.snp.makeConstraints { [weak self] make in
            guard let self = self else { return }
            make.width.equalTo(200)
            make.height.equalTo(21)
            make.left.equalTo(self.imgLeft.snp.right)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        self.labTotalYield.snp.makeConstraints { [weak self] make in
            guard let self = self else { return }
            make.height.equalTo(21)
            make.left.equalTo(self.labYield.snp.right)
            make.right.equalTo(self.labStep.snp.left)
            make.centerY.equalTo(self.topView.snp.centerY)
        }
        
        /// 底部视图
        self.bottomView.snp.makeConstraints { make in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(38)
        }
        
        self.btnBuy.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(106.5)
            make.height.equalTo(36.5)
            make.left.equalTo(Setting.K_APP_SAFETY_NAV_HEIGHT)
            make.centerY.equalTo(self.bottomView.snp.centerY)
        }
        
        self.btnBuyFall.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(106.5)
            make.height.equalTo(36.5)
            make.left.equalTo(self.btnBuy.snp.right).offset(25)
            make.centerY.equalTo(self.bottomView.snp.centerY)
        }
        
        self.btnHold.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(106.5)
            make.height.equalTo(36.5)
            make.left.equalTo(self.btnBuyFall.snp.right).offset(25)
            make.centerY.equalTo(self.bottomView.snp.centerY)
        }
        
        self.btnSell.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(106.5)
            make.height.equalTo(36.5)
            make.left.equalTo(self.btnHold.snp.right).offset(25)
            make.centerY.equalTo(self.bottomView.snp.centerY)
        }
        
        self.btnShare.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(106.5)
            make.height.equalTo(36.5)
            make.right.equalTo(-15 - Setting.K_APP_SAFETY_HEIGHT)
            make.centerY.equalTo(self.bottomView.snp.centerY)
        }
        
        /// 右边指标切换
        self.rightView.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.right.equalTo(self.topView.snp.right)
            make.width.equalTo(right_view_width)
            make.top.equalTo(self.topView.snp.bottom)
            make.bottom.equalTo(self.bottomView.snp.top)
        }
        
        /// 主图
        self.combineLineStickChart.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.left.equalTo(Setting.K_APP_SAFETY_NAV_HEIGHT)
            make.right.equalTo(self.rightView.snp.left)
            make.top.equalTo(self.topView.snp.bottom)
            make.bottom.equalTo(self.combineLineChare.snp.top)
        }
        
        self.labMATitle.snp.makeConstraints { make in
            make.left.equalTo(5)
            make.top.equalTo(-2)
            make.width.equalTo(180)
            make.height.equalTo(18)
        }
        
        self.topKpiView.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.top.equalTo(0)
            make.right.equalTo(-15 - right_view_width)
            make.height.equalTo(18)
        }
        
        /// 副图
        self.combineLineChare.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.left.equalTo(self.combineLineStickChart.snp.left)
            make.right.equalTo(self.rightView.snp.left)
            make.height.equalTo(80)
            make.bottom.equalTo(self.bottomView.snp.top)
        }
        
        self.labVolumeTitle.snp.makeConstraints { make in
            make.left.equalTo(5)
            make.top.equalTo(-8)
            make.width.equalTo(180)
            make.height.equalTo(18)
        }
        
        self.bottomKpiView.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.top.equalTo(-8)
            make.right.equalTo(-15-right_view_width)
            make.height.equalTo(18)
        }
        
        /// 十字线
        self.labVerticalLine.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(0.5)
            make.right.equalTo(0)
            make.top.equalTo(self.combineLineStickChart.snp.top)
            make.bottom.equalTo(self.combineLineChare.snp.bottom)
        }
        
        self.labHorizontalLine.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.left.equalTo(self.combineLineStickChart.snp.left).offset(10)
            make.right.equalTo(self.combineLineStickChart.snp.right)
            make.height.equalTo(0.5)
            make.top.equalTo(0)
        }
        
        self.labHorizontalLeft.snp.makeConstraints {[weak self] make in
            guard let self = self else { return }
            make.width.equalTo(35)
            make.left.equalTo(self.combineLineStickChart.snp.left)
            make.height.equalTo(15)
            make.top.equalTo(0)
        }
        
        super.updateConstraints()
    }
    
    
    /// 添加视图
    override func setupViews() {
        
        //顶部视图
        self.addSubview(self.topView)
        self.topView.addSubview(self.btnBack)
        self.topView.addSubview(self.imgLogo)
        self.topView.addSubview(self.imgLeft)
        self.topView.addSubview(self.imgRight)
        self.topView.addSubview(self.labStep)
        self.topView.addSubview(self.labYield)
        self.topView.addSubview(self.labTotalYield)
        
        //底部视图
        self.addSubview(self.bottomView)
        self.bottomView.addSubview(self.btnBuy)
        self.bottomView.addSubview(self.btnBuyFall)
        self.bottomView.addSubview(self.btnHold)
        self.bottomView.addSubview(self.btnSell)
        self.bottomView.addSubview(self.btnShare)
        
        //指标图
        self.addSubview(self.rightView)
        
        //行情主图
        self.addSubview(self.combineLineStickChart)
        self.combineLineStickChart.addSubview(self.labMATitle)
        self.combineLineStickChart.addSubview(self.topKpiView)
        
        //行情副图
        self.addSubview(self.combineLineChare)
        self.combineLineChare.addSubview(self.labVolumeTitle)
        self.combineLineChare.addSubview(self.bottomKpiView)
        
        //十字线
        self.addSubview(self.labVerticalLine)
        self.addSubview(self.labHorizontalLine)
        self.addSubview(self.labHorizontalLeft)
        
        //添加手势
        let longGest = UILongPressGestureRecognizer.init(target: self, action: #selector(longGestAction(sender:)))
        longGest.minimumPressDuration = TimeInterval.init(1.0)
        self.addGestureRecognizer(longGest)
        
        //更新显示
        self.updateUIFor(Value: .zero)
        
        //重置
        self.resetUI()
        
        setNeedsUpdateConstraints()
    }
    
    
    /// 绑定事件
    override func bindViewModel() {
        
        /// 行情加载
        self.viewModel?.gameMarketListCommand.executionSignals.switchToLatest()?.subscribeNext({[weak self] (input:Any?) in
            //行情数据
            if let _arrTemp = input as? [GameMarketModel] {
                //初始加载60条
                if _arrTemp.count > 60 {
                    self?.arrChartData = Array(_arrTemp.prefix(60))
                    self?.arrOtherData = Array(_arrTemp.suffix(from: 60))
                }
                else{
                    self?.arrChartData = _arrTemp
                    self?.arrOtherData.removeAll()
                }
            }
            else{
                self?.arrChartData.removeAll()
                self?.arrOtherData.removeAll()
            }
            
            //指标数据处理
            DispatchQueue.main.async {
                self?.setMainCombineLineData(isChange: true)
                self?.setCombineLineData(isChange: true)
            }
        })
        
        /// 副图指标切换
        self.viewModel?.gameMarketKpiChangeCommand.executionSignals.switchToLatest().subscribeNext({[weak self] (_input:Any?) in
            guard let (_index,_title) = _input as? (Int,String) else { return }
            
            if _title == "MACD" {
                self?.labVolumeTitle.text = "MACD(12,26,9)"
            }
            else if _title == "KDJ" {
                self?.labVolumeTitle.text = "KDJ(9,3,3)"
            }
            else {
                self?.labVolumeTitle.text = _title
            }
            
            self?.minorCurrentIndex = _index
            self?.setCombineLineData(isChange: true,andIndex: _index)
            
            //播放声音
            PlaySound.manager.playVoice(strVoiceName: "game_botton_sound_2")
        })
    }
    
    
    //MARK: - lazy load
    /// 行情数据
    private lazy var arrChartData = [GameMarketModel]()
    private lazy var arrOtherData = [GameMarketModel]()
    
    /// 副图当前指标索引
    private lazy var minorCurrentIndex:Int = 0
    
    /// 主图当前指标索引
    private lazy var mainCurrentIndex:Int = 0
    
    /// 主图指标数据
    private lazy var dicKpiMainData = [String:[Double]]()
    
    /// 副图指标数据
    private lazy var dicKpiData = [String:[Double]]()
    
    /// 买入记录
    private lazy var arrBuyData = [Double]()
    /// 买入方向 1买涨 -1买跌(期货是双向操作)
    private lazy var operatingDirection:Int = 1
    /// 已开始游戏
    private lazy var isAction = false
    
    //MARK: 十字线
    /// 垂直线
    private lazy var labVerticalLine:YYLabel = {
        autoreleasepool {
            let _line = BaseView.createLable(rect: .zero,
                                             text: nil,
                                             textColor: nil,
                                             font: nil,
                                             backgroundColor:MarketSetting.highlightColor)
            _line.isHidden = true
            return _line
        }
    }()
    
    /// 水平线右边值
    private lazy var labHorizontalLeft:YYLabel = {
        autoreleasepool {
            let _line = BaseView.createLable(rect: .zero,
                                             text: "0.00",
                                             textColor: UIColor.init().colorFromHexInt(hex: 0xffffff, alpha: 0.6),
                                             font: UIFont.systemFont(ofSize: 8),
                                             backgroundColor: MarketSetting.highlightColor)
            _line.isHidden = true
            return _line
        }
    }()
    
    /// 水平线
    private lazy var labHorizontalLine:YYLabel = {
        autoreleasepool {
            let _line = BaseView.createLable(rect: .zero,
                                             text: nil,
                                             textColor: nil,
                                             font: nil,
                                             backgroundColor: MarketSetting.highlightColor)
            _line.isHidden = true
            return _line
        }
    }()
    
    //MARK: 顶部视图
    /// 顶部视图
    private lazy var topView:UIView = {
        autoreleasepool {
            let _v = BaseView.createView(rect: .zero,
                                         backgroundColor: UIColor.clear)
            
            let _bgImg = UIImageView.init(image: YYImage.init(named: "game_head.png"))
            _v.addSubview(_bgImg)
            _bgImg.snp.makeConstraints { make in
                make.edges.equalTo(_v)
            }
            
            return _v
        }
    }()
    
    private lazy var btnBack:UIButton = {
        autoreleasepool {
            let _btn = BaseView.createBtn(rect: .zero,
                                          strTitle: nil,
                                          titleColor: nil,
                                          txtFont: UIFont.systemFont(ofSize: 16, weight: .medium),
                                          image: nil,
                                          backgroundColor: nil,
                                          borderColor: nil,
                                          cornerRadius: 0,
                                          isRadius: false,
                                          backgroundImage: YYImage.init(named: "game_back_btn.png"),
                                          borderWidth: 0)
            
            _btn.rac_signal(for: .touchUpInside).subscribeNext {[weak self] (_:Any?) in
                guard let self = self else { return }
                
                //播放声音
                PlaySound.manager.playVoice(strVoiceName: "game_button_sound")
                
                //提前结束，提示
                if self.isAction == true && self.arrOtherData.count > 0 {
                    Utils.shareInstance().showBoxFor(ViewController: self.viewController!,
                                                     andMessage: "是否提前结束游戏？",
                                                     andOK: "确定",
                                                     andOKBlock: { (_:UIAlertAction) -> (Void) in
                        //计算收益
                        self.rateCount(Value: nil)
                        
                        //还原设备方向
                        Utils.shareInstance().defaultDirection()
                        self.viewController?.navigationController?.popViewController(animated: true)
                    },
                                                     andCancle: "取消")
                }
                else{
                    //退出
                    Utils.shareInstance().defaultDirection()
                    self.viewController?.navigationController?.popViewController(animated: true)
                }
            }
            
            return _btn
        }
    }()
    
    private lazy var imgLogo:UIImageView = {
        autoreleasepool {
            return UIImageView.init(image: YYImage.init(named:"game_logo.png"))
        }
    }()
    
    private lazy var imgLeft:UIImageView = {
        autoreleasepool {
            let _img = UIImageView.init(image: YYImage.init(named:"game_icon.png"))
            _img.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2))
            return _img
        }
    }()
    
    private lazy var imgRight:UIImageView = {
        autoreleasepool {
            let _img = UIImageView.init(image: YYImage.init(named:"game_icon.png"))
            _img.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
            return _img
        }
    }()
    
    private lazy var labStep:YYLabel = {
        autoreleasepool {
            let _lab = BaseView.createLable(rect: .zero,
                                            text: "剩余步值:【30】",
                                            textColor: UIColor.white,
                                            font: _font,
                                            andTextAlign: .right)
            return _lab
        }
    }()
    
    /// 当前收益率
    private lazy var labYield:YYLabel = {
        autoreleasepool {
            let _lab = BaseView.createLable(rect: .zero,
                                            text: "当前收益率:【0.00%】",
                                            textColor: UIColor.white,
                                            font: _font)
            return _lab
        }
    }()
    
    /// 累计收益率
    private lazy var labTotalYield:YYLabel = {
        autoreleasepool {
            let _lab = BaseView.createLable(rect: .zero,
                                            text: "累计收益率:【0.00%】",
                                            textColor: UIColor.white,
                                            font: _font,
                                            andTextAlign: .center)
            return _lab
        }
    }()
    
    //MARK: 底部视图
    /// 底部视图
    private lazy var bottomView:UIView = {
        autoreleasepool {
            let _v = BaseView.createView(rect: .zero,
                                         backgroundColor: UIColor.init().colorFromHexInt(hex: 0x8340A1))
            
            let _bgImg = UIImageView.init(image: YYImage.init(named: "game_foot.png"))
            _v.addSubview(_bgImg)
            _bgImg.snp.makeConstraints { make in
                make.edges.equalTo(_v)
            }
            
            return _v
        }
    }()
    
    private lazy var btnBuy:UIButton = {
        autoreleasepool {
            let _btn = BaseView.createBtn(rect: .zero,
                                          strTitle: "看多",
                                          titleColor: UIColor.white,
                                          txtFont: _font,
                                          image: nil,
                                          backgroundColor: nil,
                                          borderColor: UIColor.white,
                                          cornerRadius: 0,
                                          isRadius: false,
                                          backgroundImage: YYImage.init(named: "game_but_sell.png"),
                                          borderWidth: 0)
            
            _btn.rac_signal(for: .touchUpInside).subscribeNext {[weak self] (_input:Any?) in
                guard let self = self else { return }
                self.addNewLineDataFor(Type:1,andDirection:1)
            }
            
            return _btn
        }
    }()
    
    private lazy var btnBuyFall:UIButton = {
        autoreleasepool {
            let _btn = BaseView.createBtn(rect: .zero,
                                          strTitle: "看空",
                                          titleColor: UIColor.white,
                                          txtFont: UIFont.systemFont(ofSize: 18, weight: .bold),
                                          image: nil,
                                          backgroundColor: nil,
                                          borderColor: UIColor.white,
                                          cornerRadius: 0,
                                          isRadius: false,
                                          backgroundImage: YYImage.init(named: "game_but_buy.png"),
                                          borderWidth: 0)
            
            _btn.rac_signal(for: .touchUpInside).subscribeNext {[weak self] (_input:Any?) in
                guard let self = self else { return }
                self.addNewLineDataFor(Type:1,andDirection:-1)
            }
            
            return _btn
        }
    }()
    
    private lazy var btnSell:UIButton = {
        autoreleasepool {
            let _btn = BaseView.createBtn(rect: .zero,
                                          strTitle: "平仓",
                                          titleColor: UIColor.white,
                                          txtFont: _font,
                                          image: nil,
                                          backgroundColor: nil,
                                          borderColor: UIColor.white,
                                          cornerRadius: 0,
                                          isRadius: false,
                                          backgroundImage: YYImage.init(named: "game_but_hold.png"),
                                          borderWidth: 0)
            
            _btn.rac_signal(for: .touchUpInside).subscribeNext {[weak self] (_input:Any?) in
                guard let self = self else { return }
                if self.arrBuyData.count <= 0 {
                    SVProgressHUD.showInfo(withStatus: "请买入后再卖出")
                    return
                }
                
                //添加数据
                self.addNewLineDataFor(Type:-1, andDirection: nil)
            }
            
            return _btn
        }
    }()
    
    private lazy var btnHold:UIButton = {
        autoreleasepool {
            let _btn = BaseView.createBtn(rect: .zero,
                                          strTitle: "观望",
                                          titleColor: UIColor.white,
                                          txtFont: _font,
                                          image: nil,
                                          backgroundColor:nil,
                                          borderColor: UIColor.white,
                                          cornerRadius: 0,
                                          isRadius: false,
                                          backgroundImage: YYImage.init(named: "game_but_hold.png"),
                                          borderWidth: 0)
            
            _btn.rac_signal(for: .touchUpInside).subscribeNext {[weak self] (_:Any?) in
                guard let self = self else { return }
                self.addNewLineDataFor(Type:0, andDirection: nil)
            }
            
            return _btn
        }
    }()
    
    private lazy var btnShare:UIButton = {
        autoreleasepool {
            let _btn = BaseView.createBtn(rect: .zero,
                                          strTitle: nil,
                                          titleColor: nil,
                                          txtFont: nil,
                                          image: nil,
                                          backgroundColor:nil,
                                          borderColor: nil,
                                          cornerRadius: 0,
                                          isRadius: false,
                                          backgroundImage: YYImage.init(named: "game_share.png"),
                                          borderWidth: 0)
            
            _btn.rac_signal(for: .touchUpInside).subscribeNext {[weak self] (_:Any?) in
                guard let self = self else { return }
                //                if let _vc = self.viewController as? BaseViewController {
                //                    _vc.showShareView(strShareTitle:"K线角斗士",
                //                                      strShareUrl:"https://apps.apple.com/cn/app/id1529401844",
                //                                      strShareDescription:"不服？来比划比划！！！",
                //                                      andShowAnimation:true)
                //                }
                SVProgressHUD.showInfo(withStatus: "分享")
            }
            
            return _btn
        }
    }()
    
    /// 右边副图指标
    private lazy var rightView:KLineRightView = {
        autoreleasepool {
            let _v = KLineRightView.init(ViewModel: self.viewModel!)
            _v.backgroundColor = bg_color
            _v.minorCurrentIndex = self.minorCurrentIndex
            return _v
        }
    }()
    
    //MARK: 主行情图
    /// 主行情图
    private lazy var combineLineStickChart:CombinedChartView = {[weak self] in
        autoreleasepool {
            let _stChartView = CombinedChartView.init()
            
            //缩放样式
            MarketSetting.setZoomStyleFor(Chart: _stChartView)
            
            //空视图样式
            MarketSetting.setEmptyStyleFor(Chart: _stChartView)
            
            //左边刻度样式
            MarketSetting.setLeftCalibrationStyleFor(Chart: _stChartView, andShowCount: 7)
            
            
            //底部横轴样式
            MarketSetting.setBottomCalibrationStyleFor(Chart: _stChartView,
                                                       andIsShow: false,
                                                       withShowCount: 0)
            
            //整体样式
            MarketSetting.setGradStyleFor(Chart: _stChartView,
                                          withBGColor: bg_color,
                                          withEdgeInsets: .init(top: 0, left: 0, bottom: 0, right: 0),
                                          andDelegate: self)
            
            return _stChartView
        }
    }()
    
    /// 主图MA标题
    private lazy var labMATitle:YYLabel = {
        autoreleasepool {
            let _lab = BaseView.createLable(rect: .zero,
                                            text: "MA(5,10,15,30)",
                                            textColor: MarketSetting.labelTextColor,
                                            font: UIFont.systemFont(ofSize: 12))
            
            return _lab
        }
    }()
    
    /// 主图指标信息视图
    private lazy var topKpiView:UIView = {
        autoreleasepool {
            let _v = BaseView.createView(rect: .zero)
            let _w = (Setting.K_APP_HEIGHT - right_view_width - Setting.K_APP_SAFETY_HEIGHT - (Setting.K_APP_SAFETY_NAV_HEIGHT - 20)) / 4
            _v.isHidden = true
            
            //MARK:ma5
            let _ma5p = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                            backgroundColor:MarketSetting.dif_color,
                                            isRadius: true,
                                            cornerRadius: 2.5,
                                            andBorder: 0, andBorderColor: nil)
            _v.addSubview(_ma5p)
            _ma5p.snp.makeConstraints { make in
                make.left.equalTo(10)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            var tag = 1
            let _ma5 = BaseView.createLable(rect: .zero,
                                            text: "MA5:0.00",
                                            textColor: MarketSetting.labelTextColor,
                                            font: UIFont.systemFont(ofSize: 12))
            _ma5.tag = tag
            
            _v.addSubview(_ma5)
            _ma5.snp.makeConstraints { make in
                make.left.equalTo(_ma5p.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            //MARK:ma10
            let _ma10p = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                             backgroundColor: MarketSetting.dea_color,
                                             isRadius: true,
                                             cornerRadius: 2.5,
                                             andBorder: 0, andBorderColor: nil)
            _v.addSubview(_ma10p)
            _ma10p.snp.makeConstraints { make in
                make.left.equalTo(_ma5.snp.right)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            tag = 2
            let _ma10 = BaseView.createLable(rect: .zero,
                                             text: "MA10:0.00",
                                             textColor: MarketSetting.labelTextColor,
                                             font: UIFont.systemFont(ofSize: 12))
            _ma10.tag = tag
            
            _v.addSubview(_ma10)
            _ma10.snp.makeConstraints { make in
                make.left.equalTo(_ma10p.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            //MARK:ma15
            let _ma15p = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                             backgroundColor: MarketSetting.kmacd_color,
                                             isRadius: true,
                                             cornerRadius: 2.5,
                                             andBorder: 0, andBorderColor: nil)
            _v.addSubview(_ma15p)
            _ma15p.snp.makeConstraints { make in
                make.left.equalTo(_ma10.snp.right)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            tag = 3
            let _ma15 = BaseView.createLable(rect: .zero,
                                             text: "MA15:0.00",
                                             textColor: MarketSetting.labelTextColor,
                                             font: UIFont.systemFont(ofSize: 12))
            _ma15.tag = tag
            
            _v.addSubview(_ma15)
            _ma15.snp.makeConstraints { make in
                make.left.equalTo(_ma15p.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            //MARK:ma30
            let _ma30p = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                             backgroundColor: MarketSetting.kother_color,
                                             isRadius: true,
                                             cornerRadius: 2.5,
                                             andBorder: 0, andBorderColor: nil)
            _v.addSubview(_ma30p)
            _ma30p.snp.makeConstraints { make in
                make.left.equalTo(_ma15.snp.right)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            tag = 4
            let _ma30 = BaseView.createLable(rect: .zero,
                                             text: "MA30:0.00",
                                             textColor: MarketSetting.labelTextColor,
                                             font: UIFont.systemFont(ofSize: 12))
            _ma30.tag = tag
            
            _v.addSubview(_ma30)
            _ma30.snp.makeConstraints { make in
                make.left.equalTo(_ma30p.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            return _v
        }
    }()
    
    //MARK: 副行情图
    /// 副行情图
    private lazy var combineLineChare:CombinedChartView = {[weak self] in
        autoreleasepool {
            let _ccv = CombinedChartView.init()
            
            //设置动画时间
            _ccv.animate(xAxisDuration:MarketSetting.timeInterval)
            
            //底部横轴样式
            MarketSetting.setBottomCalibrationStyleFor(Chart: _ccv,
                                                       andIsShow: false,
                                                       withShowCount: 0)
            
            //缩放样式
            MarketSetting.setZoomStyleFor(Chart: _ccv)
            
            //空视图样式
            MarketSetting.setEmptyStyleFor(Chart: _ccv)
            
            //左边刻度样式
            MarketSetting.setLeftCalibrationStyleFor(Chart: _ccv, andShowCount: 3)
            
            //整体样式
            MarketSetting.setGradStyleFor(Chart: _ccv,
                                          withBGColor: bg_color,
                                          withEdgeInsets: .init(top: 0, left: 9.5, bottom: 0, right: 0),
                                          andDelegate: self)
            
            return _ccv
        }
    }()
    
    /// 成交量
    private lazy var labVolumeTitle:YYLabel = {
        autoreleasepool {
            let _lab = BaseView.createLable(rect: .zero,
                                            text: "成交量",
                                            textColor: MarketSetting.labelTextColor,
                                            font: UIFont.systemFont(ofSize: 12))
            return _lab
        }
    }()
    
    /// 底部指标详情
    private lazy var bottomKpiView:UIView = {
        autoreleasepool {
            let _v = BaseView.createView(rect: .zero)
            let _w = (Setting.K_APP_HEIGHT - right_view_width - Setting.K_APP_SAFETY_HEIGHT - (Setting.K_APP_SAFETY_NAV_HEIGHT - 20)) / 3
            _v.isHidden = true
            
            //MARK:DIF
            let _difp = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                            backgroundColor: MarketSetting.dif_color,
                                            isRadius: true,
                                            cornerRadius: 2.5,
                                            andBorder: 0, andBorderColor: nil)
            _v.addSubview(_difp)
            _difp.snp.makeConstraints { make in
                make.left.equalTo(10)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            var tag = 1
            let _dif = BaseView.createLable(rect: .zero,
                                            text: "DIF:0.00",
                                            textColor: MarketSetting.labelTextColor,
                                            font: UIFont.systemFont(ofSize: 12))
            _dif.tag = tag
            
            _v.addSubview(_dif)
            _dif.snp.makeConstraints { make in
                make.left.equalTo(_difp.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            //MARK:DEA
            let _deap = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                            backgroundColor: MarketSetting.dea_color,
                                            isRadius: true,
                                            cornerRadius: 2.5,
                                            andBorder: 0, andBorderColor: nil)
            _v.addSubview(_deap)
            _deap.snp.makeConstraints { make in
                make.left.equalTo(_dif.snp.right)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            tag = 2
            let _dea = BaseView.createLable(rect: .zero,
                                            text: "DEA:0.00",
                                            textColor: MarketSetting.labelTextColor,
                                            font: UIFont.systemFont(ofSize: 12))
            _dea.tag = tag
            
            _v.addSubview(_dea)
            _dea.snp.makeConstraints { make in
                make.left.equalTo(_deap.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            //MARK:MACD
            let _macdp = BaseView.createView(rect: .init(x: 0, y: 0, width: 5, height: 5),
                                             backgroundColor: MarketSetting.kmacd_color,
                                             isRadius: true,
                                             cornerRadius: 2.5,
                                             andBorder: 0, andBorderColor: nil)
            _v.addSubview(_macdp)
            _macdp.snp.makeConstraints { make in
                make.left.equalTo(_dea.snp.right)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.height.equalTo(5)
            }
            
            tag = 3
            let _macd = BaseView.createLable(rect: .zero,
                                             text: "MACD:0.00",
                                             textColor: MarketSetting.labelTextColor,
                                             font: UIFont.systemFont(ofSize: 12))
            _macd.tag = tag
            
            _v.addSubview(_macd)
            _macd.snp.makeConstraints { make in
                make.left.equalTo(_macdp.snp.right).offset(3)
                make.centerY.equalTo(_v.snp.centerY)
                make.width.equalTo(_w)
            }
            
            return _v
        }
    }()
}


//MARK: -
extension KLineMainView {
    
    /// 重置UI设置
    private func resetUI(){
        //[S]还原初始化
        self.arrBuyData.removeAll()
        self.isAction = false
        self.minorCurrentIndex = 0
        self.mainCurrentIndex = 0
        self.labYield.text = "当前收益率:【0.00%】"
        self.labStep.text = "剩余步值【30】"
        self.labVolumeTitle.text = "成交量"
        self.operatingDirection = 1
        //[E]
        
        //[S] 重置缩放
        let _scale:CGFloat = 0.7
        self.combineLineStickChart.setScaleMinima(_scale, scaleY: 1)
        self.combineLineStickChart.viewPortHandler.setMaximumScaleX(_scale)
        
        self.combineLineChare.setScaleMinima(_scale, scaleY: 1)
        self.combineLineChare.viewPortHandler.setMaximumScaleX(_scale)
        //[E]
        
        //[S] 右边指标视图
        self.rightView.minorCurrentIndex = 0
        self.rightView.reloadSet()
        //[E]
    }
    
    /// 加载数据
    private func loadData(){
        //加载数据
        let _code = MarketSetting.arrCodes.randomElement()
        let _time = MarketSetting.arrTimes.randomElement()
        self.viewModel?.gameMarketListCommand.execute((_code,_time,size_count))
    }
    
    
    /// 新增数据
    /// - Parameters:
    ///   - t: 1 buy -1 sell 0 观望
    ///   - d: 买入方向 1买涨 -1买跌(期货是双向操作)
    private func addNewLineDataFor(Type t:Int,
                                   andDirection d:Int?){
        if self.arrOtherData.count > 0 {
            
            //播放声音
            PlaySound.manager.playVoice(strVoiceName: "game_botton_sound_2")
            
            let model = self.arrOtherData.first
            self.arrChartData.append(model!)
            self.arrOtherData.removeFirst()
            
            //更新主副图表
            self.setMainCombineLineData(isChange: false)
            self.setCombineLineData(isChange: false,andIndex: self.minorCurrentIndex)
            
            //更新缩放级别
            let _scale:CGFloat = (0.7/60) * CGFloat(self.arrChartData.count)
            self.combineLineStickChart.setScaleMinima(_scale, scaleY: 1)
            self.combineLineStickChart.viewPortHandler.setMaximumScaleX(_scale)
            
            self.combineLineChare.setScaleMinima(_scale, scaleY: 1)
            self.combineLineChare.viewPortHandler.setMaximumScaleX(_scale)
            
            self.labStep.text = "剩余步值【\(self.arrOtherData.count)】"
            self.isAction = true
            
            //操作处理
            if t == 1 {
                self.arrBuyData.append(Double.init(model!.low ?? "0.00")!)
                
                //当前操作方向与之前方向不一致时，应先平仓后再转向操作
                if let _diretcion = d {
                    if self.operatingDirection != d {
                        //转向操作，强制平仓
                        self.rateCount(Value: Double.init(model!.high ?? "0.00")!)
                        
                        //设置新的买卖方向
                        self.operatingDirection = _diretcion
                    }
                    else{
                        self.operatingDirection = _diretcion
                    }
                }
            }
            else if t == -1 {
                //计算收益
                self.rateCount(Value: Double.init(model!.high ?? "0.00")!)
            }
            
            //游戏结束
            if self.arrOtherData.count <= 0 {
                Utils.shareInstance().showBoxFor(ViewController: self.viewController!,
                                                 andMessage: "游戏结束",
                                                 andOK: "再来一局",
                                                 andOKBlock: { (_:UIAlertAction) -> (Void) in
                    //重置UI
                    self.resetUI()
                    
                    //重新加载数据
                    self.loadData()
                },
                                                 andCancle: "结束",
                                                 withInfo:self.labYield.text!.replacingOccurrences(of: "当前", with: "本局"))
            }
        }
        else{
            print("没有数据可添加了")
        }
    }
    
    
    /// 计算收益
    /// - Parameters:
    ///   - v: Double? 不存在强制平仓
    private func rateCount(Value v:Double?){
        /**
         low 点做 buy，high 点做 sell
         初始资金 = 10000
         收益率 ＝ ((净值 / 初始资金) - 1) * 100
         */
        
        var _sells = Double.zero
        let _buys = self.arrBuyData.reduce(0,+)
        
        //正常平仓
        if let _sellValue = v {
            _sells = Double(self.arrBuyData.count) * _sellValue
        }
        //强制平仓
        else{
            //平仓价,最后一条数据的最高价为平仓价
            let _sell:Double = Double.init(self.arrChartData.last?.high ?? "0.00")!
            _sells = Double(self.arrBuyData.count) * _sell
        }
        
        var _earnings:Double = self.tmoney
        //买涨
        if self.operatingDirection == 1 {
            _earnings += _sells - _buys
        }
        //买跌
        else{
            _earnings += _buys - _sells
        }
        
        let yield:Double = _earnings / self.tmoney - 1
        self.updateUIFor(Value: yield)
        
        //清除
        self.arrBuyData.removeAll()
    }
    
    
    /// 当前收益
    /// - Parameter v: Double
    private func updateUIFor(Value v:Double){
        
        //当前收益率
        var _strFull = String.init(format:"当前收益率:【%.2f%@】",v * 100,"%")
        self.labYield.attributedText = Utils.shareInstance().setAttributeStringText(strFullText: _strFull,
                                                                                    andFullTextFont: _font,
                                                                                    andFullTextColor: UIColor.white,
                                                                                    withChangeText: String.init(format:"%.2f%@",v * 100,"%"),
                                                                                    withChangeFont: _font,
                                                                                    withChangeColor: v >= 0 ? (v == 0 ? UIColor.white : MarketSetting.red_color) : MarketSetting.greent_color)
        
        //累计收益率
        var _v:Double = UserDefaults.standard.double(forKey: MarketSetting.total_yield_key)
        _v += v
        _strFull = String.init(format:"累计收益率:【%.2f%@】",_v * 100,"%")
        self.labTotalYield.attributedText = Utils.shareInstance().setAttributeStringText(strFullText: _strFull,
                                                                                         andFullTextFont: _font,
                                                                                         andFullTextColor: UIColor.white,
                                                                                         withChangeText: String.init(format:"%.2f%@",_v * 100,"%"),
                                                                                         withChangeFont: _font,
                                                                                         withChangeColor: _v >= 0 ? (_v == 0 ? UIColor.white : MarketSetting.red_color) : MarketSetting.greent_color)
        
        //更新累计收益率
        UserDefaults.standard.setValue(_v, forKey: MarketSetting.total_yield_key)
        DispatchQueue.global().async {
            UserDefaults.standard.synchronize()
        }
    }
}



//MARK: - 十字线(自定义)
extension KLineMainView {
    
    /// 长按手势
    /// - Parameter sender: UILongPressGestureRecognizer
    @objc private func longGestAction(sender:UILongPressGestureRecognizer) {
        
        let transPoint:CGPoint = sender.location(in: self.combineLineStickChart)
        let _maxX = Setting.K_APP_HEIGHT - right_view_width - Setting.K_APP_SAFETY_NAV_HEIGHT
        if transPoint.x > _maxX || transPoint.x < Setting.K_APP_SAFETY_NAV_HEIGHT - 10 {
            return
        }
        
        switch sender.state {
            //MARK:开始
        case .began:
            let (_,_newPoint) = self.updatePositionFor(Point: transPoint)
            self.labVerticalLine.center = .init(x: _newPoint.x + Setting.K_APP_SAFETY_NAV_HEIGHT, y: self.labVerticalLine.centerY)
            
            if transPoint.y >= self.combineLineStickChart.top && transPoint.y <= self.combineLineChare.bottom  {
                self.labHorizontalLine.center = .init(x: self.labHorizontalLine.width * 0.5 + Setting.K_APP_SAFETY_NAV_HEIGHT, y: transPoint.y)
                self.updateRightViewFor(Point: transPoint)
            }
            
            self.labHorizontalLeft.isHidden = false
            self.labHorizontalLine.isHidden = false
            self.labVerticalLine.isHidden = false
            self.bottomKpiView.isHidden = self.minorCurrentIndex == 0 ? true : false
            self.topKpiView.isHidden = false
            
            self.labMATitle.isHidden = true
            self.labVolumeTitle.isHidden = true
            break
            
            //MARK:手势改变
        case .changed:
            let (_m,_newPoint) = self.updatePositionFor(Point: transPoint)
            
            if let _model = _m {
                self.labVerticalLine.center = .init(x: _newPoint.x + Setting.K_APP_SAFETY_NAV_HEIGHT, y: self.labVerticalLine.centerY)
                if transPoint.y >= self.combineLineStickChart.top && transPoint.y <= self.combineLineChare.bottom  {
                    self.labHorizontalLine.center = .init(x: self.labHorizontalLine.width * 0.5 + Setting.K_APP_SAFETY_NAV_HEIGHT, y: transPoint.y)
                    self.updateRightViewFor(Point: transPoint)
                }
                
                //更新顶部
                self.updateTopViewFor(Index: Int(_model.x))
                
                //更新底部
                self.updateBottomViewFor(Index: Int(_model.x))
            }
            break
            
            //MARK:其他(取消、结束...)
        default:
            self.labHorizontalLeft.isHidden = true
            self.labHorizontalLine.isHidden = true
            self.labVerticalLine.isHidden = true
            self.bottomKpiView.isHidden = true
            self.topKpiView.isHidden = true
            
            self.labMATitle.isHidden = false
            self.labVolumeTitle.isHidden = false
            
            if self.minorCurrentIndex == 0 {
                self.labVolumeTitle.text = "成交量"
            }
            break
        }
        
    }
    
    
    /// 根据手势移动的坐标获取对应K线上的坐标
    /// - Parameter p: CGPoint
    /// - Returns: (CandleChartDataEntry?,CGPoint)
    private func updatePositionFor(Point p:CGPoint) -> (CandleChartDataEntry?,CGPoint) {
        let _model:CandleChartDataEntry? = self.combineLineStickChart.getEntryByTouchPoint(point: p) as? CandleChartDataEntry
        
        var _newPoint = p
        if _model != nil {
            _newPoint = self.combineLineStickChart.getPosition(entry: _model!, axis: YAxis.AxisDependency.right)
        }
        
        return (_model,_newPoint)
    }
    
    //MARK:主图指标值
    /// 更新顶部主图指标
    /// - Parameter ix: Int
    private func updateTopViewFor(Index ix:Int) {
        
        if self.mainCurrentIndex == 0 {
            guard let(_arrMa5,_arrMa10,_arrMa15,_arrMa30) = (self.dicKpiMainData[MA.kpiType.ma5.rawValue],self.dicKpiMainData[MA.kpiType.ma10.rawValue],self.dicKpiMainData[MA.kpiType.ma15.rawValue],self.dicKpiMainData[MA.kpiType.ma30.rawValue]) as? ([Double],[Double],[Double],[Double]) else {
                return
            }
            
            let _count = self.arrChartData.count
            let _5Mindex = _count - _arrMa5.count
            let _10Mindex = _count - _arrMa10.count
            let _15Mindex = _count - _arrMa15.count
            let _30Mindex = _count - _arrMa30.count
            
            self.moveUpdateFor(View: self.topKpiView,
                               andV1: (_arrMa5.count > (ix - _5Mindex) && (ix - _5Mindex) >= 0) ? String.init(format:"MA5:%.2f",_arrMa5[ix - _5Mindex]) : "MA5:0.00",
                               andV2: (_arrMa10.count > (ix - _10Mindex) && (ix - _10Mindex) >= 0) ? String.init(format:"MA10:%.2f",_arrMa10[ix - _10Mindex]) : "MA10:0.00",
                               withV3:(_arrMa15.count > (ix - _15Mindex) && (ix - _15Mindex) >= 0) ? String.init(format:"MA15:%.2f",_arrMa15[ix - _15Mindex]) : "MA15:0.00",
                               withV4: (_arrMa30.count > (ix - _30Mindex) && (ix - _30Mindex) >= 0) ? String.init(format:"MA30:%.2f",_arrMa30[ix - _30Mindex]) : "MA30:0.00")
        }
        
    }
    
    //MARK:副图指标值
    /// 更新底部副图指标
    /// - Parameter ix: Int
    private func updateBottomViewFor(Index ix:Int) {
        
        switch self.minorCurrentIndex {
        case 0://成交量
            let arrTemp = self.dicKpiData["volume"]
            
            if arrTemp != nil && arrTemp!.count > ix {
                self.labVolumeTitle.isHidden = false
                self.bottomKpiView.isHidden = true
                self.labVolumeTitle.text = String.init(format:"成交量:%.1f",arrTemp![ix])
            }
            break
            
        case 1://MACD
            guard let(_arrDif,_arrDea,_arrMACD) = (self.dicKpiData[MACD.kpiType.dif.rawValue],self.dicKpiData[MACD.kpiType.dea.rawValue],self.dicKpiData[MACD.kpiType.macd.rawValue]) as? ([Double],[Double],[Double]) else {
                return
            }
            
            self.moveUpdateFor(View:self.bottomKpiView,
                               andV1: _arrDif.count > ix ? String.init(format:"DIF:%.2f",_arrDif[ix]) : "DIF:0.00",
                               andV2: _arrDea.count > ix ? String.init(format:"DEA:%.2f",_arrDea[ix]) : "DEA:0.00",
                               withV3: _arrMACD.count > ix ? String.init(format:"MACD:%.2f",_arrMACD[ix]) : nil,
                               withV4: nil)
            break
            
        case 2://KDJ
            guard let(_arrK,_arrD,_arrJ) = (self.dicKpiData[KDJ.kpiType.k.rawValue],self.dicKpiData[KDJ.kpiType.d.rawValue],self.dicKpiData[KDJ.kpiType.j.rawValue]) as? ([Double],[Double],[Double]) else {
                return
            }
            
            self.moveUpdateFor(View:self.bottomKpiView,
                               andV1: _arrK.count > ix ? String.init(format:"K:%.2f",_arrK[ix]) : "K:0.00",
                               andV2: _arrD.count > ix ? String.init(format:"D:%.2f",_arrD[ix]) : "D:0.00",
                               withV3: _arrJ.count > ix ? String.init(format:"J:%.2f",_arrJ[ix]) : nil,
                               withV4: nil)
            break
            
        default:
            break
        }
    }
    
    private func moveUpdateFor(View v:UIView,
                               andV1 v1:String,
                               andV2 v2:String,
                               withV3 v3:String? = nil,
                               withV4 v4:String? = nil) {
        var labV1:YYLabel?
        var labV2:YYLabel?
        var labV3:YYLabel?
        var labV4:YYLabel?
        
        for _view in v.subviews {
            switch _view.tag {
            case 1:
                labV1 = _view as? YYLabel
                
            case 2:
                labV2 = _view as? YYLabel
                
            case 3:
                labV3 = _view as? YYLabel
                
            case 4:
                labV4 = _view as? YYLabel
                
            default:
                break
            }
        }
        
        labV1?.text = v1
        labV2?.text = v2
        labV3?.text = v3
        labV4?.text = v4
    }
    
    //MARK:十字线数值
    /// 更新右边水平十字线数值
    /// - Parameter p: CGPoint
    private func updateRightViewFor(Point p:CGPoint) {
        self.labHorizontalLeft.centerY = self.labHorizontalLine.centerY
        
        var _min:Double = 0.0
        var _max:Double = 0.0
        var _unitValue:Double = 0.0
        var _haveHight:CGFloat = 0.0
        
        //匹配主图刻度值
        if p.y >= self.combineLineStickChart.top && p.y <= self.combineLineStickChart.bottom {
            _min = self.combineLineStickChart.leftAxis.axisMinimum
            _max = self.combineLineStickChart.leftAxis.axisMaximum
            
            //计算单位高度的值
            _unitValue = (_max - _min) / Double(self.combineLineStickChart.height)
            
            //拥有的单位高度
            _haveHight = p.y - self.combineLineStickChart.top
        }
        //匹配附图刻度值
        else if p.y >= self.combineLineChare.top && p.y <= self.combineLineChare.bottom {
            _min = self.combineLineChare.leftAxis.axisMinimum
            _max = self.combineLineChare.leftAxis.axisMaximum
            
            //计算单位高度的值
            _unitValue = (_max - _min) / Double(self.combineLineChare.height)
            
            //拥有的单位高度
            _haveHight = p.y - self.combineLineChare.top
        }
        
        //赋值
        if _max > 0 {
            self.labHorizontalLeft.text = String.init(format:"%.2f",_max - _unitValue * Double(_haveHight))
        }
    }
}


//MARK: - ChartViewDelegate
extension KLineMainView : ChartViewDelegate {
    
    /// 图表被移动(主、副图同时响应)
    /// https://blog.csdn.net/dianchidu6913/article/details/101228178
    /// - Parameters:
    ///   - chartView: ChartViewBase
    ///   - dX: CGFloat
    ///   - dY: CGFloat
    func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
        self.updateTouchFor(ChartView: chartView)
    }
    
    
    /// 图表被缩放
    /// - Parameters:
    ///   - chartView: ChartViewBase
    ///   - scaleX: CGFloat
    ///   - scaleY: CGFloat
    func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
        self.updateTouchFor(ChartView: chartView)
    }
    
    
    /// 同步手势
    /// - Parameter chartView: chartView description
    private func updateTouchFor(ChartView chartView:ChartViewBase){
        let srcMatrix:CGAffineTransform = chartView.viewPortHandler.touchMatrix
        
        self.combineLineStickChart.viewPortHandler.refresh(newMatrix: srcMatrix,
                                                           chart: self.combineLineStickChart,
                                                           invalidate: true)
        
        self.combineLineChare.viewPortHandler.refresh(newMatrix: srcMatrix,
                                                      chart: self.combineLineChare,
                                                      invalidate: true)
    }
}


//MARK: - 主图数据绑定
extension KLineMainView {
    
    /// 主图数据绑定
    /// - Parameter isChange: Bool
    private func setMainCombineLineData(isChange:Bool = false) {
        
        if self.arrChartData.count <= 0 { return }
        
        if self.mainCurrentIndex == 0 {
            //主图指标数据
            self.dicKpiMainData = [
                MA.kpiType.ma5.rawValue  : MA.calcMA(Model: self.arrChartData, andNmbner: 5),
                MA.kpiType.ma10.rawValue : MA.calcMA(Model: self.arrChartData, andNmbner: 10),
                MA.kpiType.ma15.rawValue : MA.calcMA(Model: self.arrChartData, andNmbner: 15),
                MA.kpiType.ma30.rawValue : MA.calcMA(Model: self.arrChartData, andNmbner: 30),
            ]
        }
        
        if self.arrChartData.count > 0 {
            //x、y轴数据
            var xValues = [String]()
            var yStockValue = [ChartDataEntry]()
            
            //MARK:股票和x轴数据
            var i = 0
            for item in self.arrChartData {
                let _strDateTime = item.day ?? Utils.shareInstance().localDateTime(Formatter: "yyyy-MM-dd HH:mm:ss")
                xValues.append(_strDateTime)
                
                let entry = CandleChartDataEntry.init(x: Double.init(i),
                                                      shadowH: Double.init(item.high ?? "0.00")!,
                                                      shadowL: Double.init(item.low ?? "0.00")!,
                                                      open: Double.init(item.open ?? "0.00")!,
                                                      close: Double.init(item.close ?? "0.00")!)
                
                yStockValue.append(entry)
                i += 1
            }
            
            if xValues.count > 0 {
                self.combineLineStickChart.xAxis.valueFormatter = IndexAxisValueFormatter.init(values: xValues)
                self.combineLineChare.xAxis.valueFormatter = IndexAxisValueFormatter.init(values: xValues)
            }
            
            //MARK:MA数据
            guard let(_arrMA5,_arrMA10,_arrMA15,_arrMA30) = (self.dicKpiMainData[MA.kpiType.ma5.rawValue],
                                                             self.dicKpiMainData[MA.kpiType.ma10.rawValue],
                                                             self.dicKpiMainData[MA.kpiType.ma15.rawValue],
                                                             self.dicKpiMainData[MA.kpiType.ma30.rawValue]) as? (
                                                                [Double],[Double],[Double],[Double]) else {
                return
            }
            
            var yMA5Values   = [ChartDataEntry]()
            var yMA10Values  = [ChartDataEntry]()
            var yMA15Values  = [ChartDataEntry]()
            var yMA30Values  = [ChartDataEntry]()
            
            //MA5
            let _count = self.arrChartData.count
            var _minIndex = (_count - _arrMA5.count)
            for i in _minIndex..<_count {
                let entry = ChartDataEntry.init(x: Double.init(i), y: _arrMA5[i - _minIndex])
                yMA5Values.append(entry)
            }
            
            //MA10
            _minIndex = (_count - _arrMA10.count)
            for i in _minIndex..<_count {
                let entry = ChartDataEntry.init(x: Double.init(i), y: _arrMA10[i - _minIndex])
                yMA10Values.append(entry)
            }
            
            //MA15
            _minIndex = (_count - _arrMA15.count)
            for i in _minIndex..<_count {
                let entry = ChartDataEntry.init(x: Double.init(i), y: _arrMA15[i - _minIndex])
                yMA15Values.append(entry)
            }
            
            //MA30
            _minIndex = (_count - _arrMA30.count)
            for i in _minIndex..<_count {
                let entry = ChartDataEntry.init(x: Double.init(i), y: _arrMA30[i - _minIndex])
                yMA30Values.append(entry)
            }
            
            //设置数据
            let data:CombinedChartData = CombinedChartData.init()
            
            //MA5,10,15,30
            let lineDS = LineChartData.init(dataSets: [
                MarketSetting.setLineDataFor(Values: yMA5Values, andColor: MarketSetting.dif_color,withName: "MA5"),
                MarketSetting.setLineDataFor(Values: yMA10Values,andColor: MarketSetting.dea_color,withName: "MA10"),
                MarketSetting.setLineDataFor(Values: yMA15Values,andColor: MarketSetting.kmacd_color, withName: "MA15"),
                MarketSetting.setLineDataFor(Values: yMA30Values,andColor: MarketSetting.kother_color, withName: "MA30"),
            ])
            
            data.lineData = lineDS
            
            //股票
            data.candleData = CandleChartData.init(dataSets:[
                MarketSetting.setStockDataSetFor(Values: yStockValue)
            ])
            
            self.combineLineStickChart.data = data
            if isChange {
                self.combineLineStickChart.animate(xAxisDuration: MarketSetting.timeInterval)
            }
            
            if let _xMax = self.combineLineStickChart.data?.xMax {
                //开局移动到最右边xMax为最大x轴值
                self.combineLineStickChart.moveViewToX(_xMax)
            }
        }
    }
    
    
}


//MARK: - 副图指标数据绑定
extension KLineMainView {
    
    /// 指标图数据绑定
    /// - Parameter isChange: isChange description
    private func setCombineLineData (isChange:Bool = false,
                                     andIndex ix:Int = 0){
        //副图指标数据
        if self.arrChartData.count > 0 {
            
            //显示刻度
            self.combineLineChare.leftAxis.enabled = true
            self.combineLineChare.setExtraOffsets(left: 11,top: 0,right: 0,bottom: 0)
            
            //MARK:成交量
            if ix == 0 {
                //不显示刻度
                self.combineLineChare.leftAxis.enabled = false
                self.combineLineChare.setExtraOffsets(left: 33,top: 0,right: 0,bottom: 0)
                
                let arrTemp:[Double] = self.arrChartData.compactMap({ ($0.volume != "" && $0.volume != nil) ? Double.init($0.volume!) : 0.00 })
                let arrColors:[UIColor] = self.arrChartData.compactMap({ Double.init($0.close ?? "0.00")! >= Double.init($0.open ?? "0.00")! ? MarketSetting.red_color : MarketSetting.greent_color })
                self.dicKpiData = ["volume":arrTemp]
                
                self.setVolumeFor(Data: arrTemp, andColors: arrColors, withChange: isChange)
            }
            //MARK:MACD
            else if ix == 1 {
                self.combineLineChare.setExtraOffsets(left: 11,top: 0,right: 0,bottom: -1.5)
                self.dicKpiData = MACD.calcMACDFor(Model: self.arrChartData)
                
                guard let(_arrDif,_arrDea,_arrMACD) = (
                    self.dicKpiData[MACD.kpiType.dif.rawValue],
                    self.dicKpiData[MACD.kpiType.dea.rawValue],
                    self.dicKpiData[MACD.kpiType.macd.rawValue]) as? (
                        [Double],[Double],[Double]) else {
                    return
                }
                
                self.setMACDFor(DIF: _arrDif, andDEA: _arrDea, andMACD: _arrMACD,withChange: isChange)
            }
            //MARK:KDJ
            else if ix == 2 {
                self.dicKpiData = KDJ.calcKDJFor(Model: self.arrChartData,andNumber: 9,andK: 3,withD: 3)
                
                guard let(_arrK,_arrD,_arrJ) = (
                    self.dicKpiData[KDJ.kpiType.k.rawValue],
                    self.dicKpiData[KDJ.kpiType.d.rawValue],
                    self.dicKpiData[KDJ.kpiType.j.rawValue]) as? (
                        [Double],[Double],[Double]) else {
                    return
                }
                
                self.setKDJFor(K: _arrK, andD: _arrD, andJ: _arrJ, withChange: isChange)
            }
        }
    }
    
    private func setVolumeFor(Data d:[Double],
                              andColors c:[UIColor],
                              withChange isChange:Bool){
        
        var arrValues = [ChartDataEntry]()
        
        //成交量
        for i in 0..<d.count {
            let entry = BarChartDataEntry.init(x: Double.init(i), y: d[i])
            arrValues.append(entry)
        }
        
        //设置数据
        let data:CombinedChartData = CombinedChartData.init()
        data.barData = BarChartData.init(dataSets: [
            MarketSetting.setBarCharSetFor(Values: arrValues, andColors: c, withName: "成交量")
        ])
        self.combineLineChare.data = data
        
        if isChange {
            self.combineLineChare.animate(xAxisDuration: MarketSetting.timeInterval)
        }
        
        if let _xMax = self.combineLineChare.data?.xMax {
            //开局移动到最右边xMax为最大x轴值
            self.combineLineChare.moveViewToX(_xMax)
        }
    }
    
    private func setMACDFor(DIF _arrDif:[Double],
                            andDEA _arrDea:[Double],
                            andMACD _arrMACD:[Double],
                            withChange isChange:Bool){
        
        var yDIFValues  = [ChartDataEntry]()
        var yDEAValues  = [ChartDataEntry]()
        var yMACDValues = [ChartDataEntry]()
        
        //DIF
        for i in 0..<_arrDif.count {
            let entry = ChartDataEntry.init(x: Double.init(i),
                                            y: _arrDif[i])
            yDIFValues.append(entry)
        }
        
        //DEA
        for i in 0..<_arrDea.count {
            let entry = ChartDataEntry.init(x: Double.init(i),
                                            y: _arrDea[i])
            yDEAValues.append(entry)
        }
        
        //MACD
        for i in 0..<_arrMACD.count {
            let entry = BarChartDataEntry.init(x: Double.init(i), y: _arrMACD[i])
            yMACDValues.append(entry)
        }
        
        //设置数据
        let data:CombinedChartData = CombinedChartData.init()
        
        //DIF,DEA
        let lineDS = LineChartData.init(dataSets: [
            MarketSetting.setLineDataFor(Values: yDIFValues,
                                         andColor: MarketSetting.dif_color,
                                         withName: "DIF"),
            MarketSetting.setLineDataFor(Values: yDEAValues,
                                         andColor: MarketSetting.dea_color,
                                         withName: "DEA")])
        data.lineData = lineDS
        
        //MACD
        data.barData = BarChartData.init(dataSets: [
            MarketSetting.setBarCharSetFor(Values: yMACDValues, withName: "MACD")
        ])
        self.combineLineChare.data = data
        
        if isChange {
            self.combineLineChare.animate(xAxisDuration: MarketSetting.timeInterval)
        }
        
        if let _xMax = self.combineLineChare.data?.xMax {
            //开局移动到最右边xMax为最大x轴值
            self.combineLineChare.moveViewToX(_xMax)
        }
    }
    
    private func setKDJFor(K _arrK:[Double],
                           andD _arrD:[Double],
                           andJ _arrJ:[Double],
                           withChange isChange:Bool){
        
        var yKValues  = [ChartDataEntry]()
        var yDValues  = [ChartDataEntry]()
        var yJValues = [ChartDataEntry]()
        
        //K
        for i in 0..<_arrK.count {
            let entry = ChartDataEntry.init(x: Double.init(i),
                                            y: _arrK[i])
            yKValues.append(entry)
        }
        
        //D
        for i in 0..<_arrD.count {
            let entry = ChartDataEntry.init(x: Double.init(i),
                                            y: _arrD[i])
            yDValues.append(entry)
        }
        
        //J
        for i in 0..<_arrJ.count {
            let entry = BarChartDataEntry.init(x: Double.init(i),
                                               y: _arrJ[i])
            yJValues.append(entry)
        }
        
        //设置数据
        let data:CombinedChartData = CombinedChartData.init()
        
        let lineDS = LineChartData.init(dataSets: [
            MarketSetting.setLineDataFor(Values: yKValues,
                                         andColor: MarketSetting.dif_color,
                                         withName: "K"),
            MarketSetting.setLineDataFor(Values: yDValues,
                                         andColor: MarketSetting.dea_color,
                                         withName: "D"),
            MarketSetting.setLineDataFor(Values: yJValues,
                                         andColor: MarketSetting.kmacd_color,
                                         withName: "J"),
        ])
        data.lineData = lineDS
        
        self.combineLineChare.data = data
        if isChange {
            self.combineLineChare.animate(xAxisDuration: MarketSetting.timeInterval)
        }
        
        if let _xMax = self.combineLineChare.data?.xMax {
            //开局移动到最右边xMax为最大x轴值
            self.combineLineChare.moveViewToX(_xMax)
        }
    }
}
